layui.define(['element', 'api', 'fast_config', 'domain_design_business', 'domain_design_default','domain_design_index', 'amis', 'utils'], function(exports) {
	"use strict";

	/**
	 * Button component
	 * */
	var MOD_NAME = 'domain_design',
		$ = layui.jquery,
        api = layui.api,
        fast_config = layui.fast_config,
        domain_design_business = layui.domain_design_business,
        domain_design_default = layui.domain_design_default,
        domain_design_index = layui.domain_design_index,
        utils = layui.utils,
        listeners = layui.listener,
        amis = layui.amis
    ;




	var domain_design = function(opt) {
		this.option = opt;
	};

	function saveDesign(option){
        // debugger
        var grid_domain_design_businessData = option.grid_domain_design_business.option.grid.getData();
        var grid_domain_design_defaultData = option.grid_domain_design_default.option.grid.getData();
        var domain_design_index_data = option.grid_domain_design_index.option.grid.getData();
        // var formObject = option.amisObj.option.amisScoped.getComponentById(getAmisId(option)).getValues();
        var formObject = option.amisObj.option.amisScoped.getComponentByName(getAmisId(option)).getValues();

        let fieldNames=[],columnNames=[];
        for(var field of grid_domain_design_businessData){
            fieldNames.push(field["fieldName"]);
            if(field["columnName"] !== "" && field["columnName"] !== undefined){
                columnNames.push(field["columnName"]);
            }

            var validation=[];
            if(field["Keyword"]){
                validation.push("Keyword");
            }
            if(field["Repeat"]){
                validation.push("Repeat");
            }
            if(field["NotEmpty"]){
                validation.push("NotEmpty");
            }
            field["validationTypeList"] = validation;
        }

        // for(var field of domain_design_index_data){
        //     indexNames.push(field["indexName"]);
        // }

        formObject["fieldList"] = grid_domain_design_businessData;
        formObject["defaultField"] = grid_domain_design_defaultData;
        formObject["indexList"] = domain_design_index_data;

        formObject["modelType"] = "domainmodel";


        const listFieldLength=fieldNames.length,newFieldListLength=new Set(fieldNames.map(item=>item)).size;
        const listColumnLength=columnNames.length,newColumnListLength=new Set(columnNames.map(item=>item)).size;
        // const listIndexLength=fieldNames.length,newIndexListLength=new Set(indexNames.map(item=>item)).size;
        if(formObject.tree && (formObject.pmodelId == undefined || formObject.pmodelId=="")){
            layer.alert('树模型必须选择父类');
        }else if(listFieldLength>newFieldListLength){
            layer.alert('英文名不可重复，请调整后保存。');
        }else if(listColumnLength>newColumnListLength){
            layer.alert('表字段不可重复，请调整后保存。');
        }else if(grid_domain_design_businessData.length<1){
            layer.alert('请先设计字段！');
        }else if(grid_domain_design_defaultData.length<1){
            layer.alert('请查看默认字段是否生成！');
        }else{
            var optionApi = {
                enableRootPath:true,
                type: "POST",
                // url: fast_config.domain.saveApi+option.treeNode.id,
                url: fast_config.moudle.domain.saveApi.format({nodeid:option.treeNode.id}),
                data: JSON.stringify(formObject),
                contentType : 'application/json;charset=UTF-8',
                success: function(data){
                    layer.msg('操作成功');
                    if(option.callback && option.callback.reloadtree && typeof option.callback.reloadtree === 'function'){
                        option.callback.reloadtree(data);
                    }
                }
            };

            api.exec(optionApi)
        }
    }

    function getModelData(option){
        var modelJson=null;
        var optionApi = {
            enableRootPath:true,
            type: "GET",
            // url: fast_config.domain.initApi+option.treeNode.id,
            url: fast_config.moudle.domain.initApi.format({nodeid:option.treeNode.id}),
            success: function(data){
                if(typeof data !== 'object' ){
                    modelJson =  JSON.parse(data);
                }
            }
        };

        api.exec(optionApi);

        return modelJson;
    }

    function appendElem(option){

        var id = "domain_design" + option.elem.slice(1);
        var domainContainerId = 'domainContainer_' + id;
        var saveId = "saveDesign_" + id;

        // <span className="buttonBox">
        //                     <button id="${saveId}" type="button"
        //                             className="layui-btn layui-btn-primary layui-btn-xs domainSave"> <span>保存</span></button>
        //                 </span>
        var domainContainer = `
            <div id="${domainContainerId}">
                <div class="layui-tab layui-tab-brief" lay-filter="docDemoTabBrief">
                    <ul class="layui-tab-title domainTabs">
                        <li class="layui-this">业务字段</li>
                        <li>默认字段</li>
                        <li>高级设置</li>
                        <li>索引</li>
                    </ul>
                    <div class="layui-tab-content" id="domainContent">
                        <div class="layui-tab-item item-pgGride layui-show" >
                            <div class="padding10">
                                <div id="${getDomainDesignBusinessId(option)}"></div>
                            </div>
                        </div>
                        <div class="layui-tab-item item-pgGride layui-show" >
                            <div class="padding10">
                                <div id="${getGridDomainDesignDefault(option)}"></div>
                            </div>
                        </div>
                        <div class="layui-tab-item" >
                            <div class="padding10">
                                <div id="${getAmisId(option)}"></div>
                            </div>
                        </div>
                        <div class="layui-tab-item item-pgGride layui-show" >
                            <div class="padding10">
                                <div id="${getDmainDesignIndex(option)}"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
		`;

        $(option.elem).append(domainContainer);
        //
        // $('#' + saveId).click(function(){
        //     saveDesign(option);
        // });
    }

    function getAmisId(option){
        var id = option.elem.slice(1);
        return 'domainAdvancedSetting_' + id;
    }
    function getDomainDesignBusinessId(option){
        var id = option.elem.slice(1);
        return 'domainBusinessFields_' + id;
    }
    function getGridDomainDesignDefault(option){
        var id = option.elem.slice(1);
        return 'domainDefaultFields_' + id;
    }
    function getDmainDesignIndex(option){
        var id = option.elem.slice(1);
        return 'domainIndexFields_' + id;
    }

    /**
	 * Button start loading
	 * */
    domain_design.prototype.render = function(opt) {
		var option = {
			elem: opt.elem,
            data: opt.data,
            treeNode: opt.treeNode,
            viewMode: opt.viewMode,
            pearBody : opt.pearBody,
            amisData: opt.amisData,
            callback: opt.callback,
            grid_domain_design_business: null,
            grid_domain_design_default: null,
            grid_domain_design_index: null
		}
        render(option);

        /**
         * 保存领域模型监听器
         * 该监听器在资源工具栏中使用
         * @param {} event
         * @param {*} spanSchema
         * @param {*} toolbrObj
         */
        function saveDomainModelResourceToolbarListener(event, spanSchema, toolbrObj){
            //当data.id有值则会选中id节点，没有则只刷新
            saveDesign(option);
        }

        /**
         * 模块装配
         */
        listeners.registerToolbarListener("saveDomainModelResourceToolbarListener", saveDomainModelResourceToolbarListener)

        return new domain_design(option);
	}

    function render(option){

        appendElem(option);
        var id = option.treeNode.tId;
        var modelJson = getModelData(option);

        var initBusinessData, initDefaultData,initDomainIndex;
        if(modelJson !=null){
            initBusinessData = modelJson.fieldList;
            initDefaultData = modelJson.defaultField;
            initDomainIndex = modelJson.indexList;
        }
        // grid;
        option.grid_domain_design_business = domain_design_business.render({
            elem: '#' + getDomainDesignBusinessId(option),
            initData: initBusinessData
        });

        option.grid_domain_design_default = domain_design_default.render({
            elem: '#' + getGridDomainDesignDefault(option),
            initData: initDefaultData
        })

        option.amisObj = amis.render({
            elem: '#' + getAmisId(option),
            schema: {
                "type": "form",
                "body": [
                    {
                        "type": "fieldset",
                        "title": "配置信息",
                        "body": [
                            {
                                "type": "list-select",
                                "name": "modelType",
                                "id": "u:7921744dbd12",
                                "label": "模型类型",
                                "options": [
                                    {
                                        "label": "实体",
                                        "value": "entity"
                                    },
                                    {
                                        "label": "值对象",
                                        "value": "vo"
                                    },
                                    {
                                        "label": "字段",
                                        "value": "field"
                                    }
                                ],
                                "value": "entity",
                                "visibleOn": "",
                                "clearValueOnHidden": false,
                                "visible": false
                            },
                            {
                                "type": "group",
                                "body": [
                                    {
                                        "type": "switch",
                                        "label": "是否树",
                                        "name": "tree",
                                        "option": "",
                                        "mode": "inline",
                                        "optionAtLeft": false,
                                        "trueValue": true,
                                        "falseValue": false,
                                        "value": false,
                                        "columnRatio": "auto",
                                        "id": "u:70a9bc86a566"
                                    },
                                    {
                                        "type": "switch",
                                        "option": "",
                                        "name": "isExtend",
                                        "label": "是否可被继承",
                                        "optionAtLeft": false,
                                        "trueValue": true,
                                        "falseValue": "false",
                                        "columnRatio": "auto",
                                        "id": "u:c51187d9cb29",
                                        "mode": "inline"
                                    },
                                    {
                                        "type": "picker",
                                        "label": "父模型",
                                        "name": "pmodelId",
                                        "joinValues": true,
                                        "valueField": "id",
                                        "labelField": "name",
                                        "source": "${platformUrl | url_decode}/api/v1/engine/domainmodel/parents?tenantId=${mid.tenantId}&tree=${tree}",
                                        "size": "lg",
                                        "pickerSchema": {
                                            "mode": "table",
                                            "name": "",
                                            "draggable": false,
                                            "headerToolbar": [
                                            ],
                                            "columns": [
                                                {
                                                    "name": "enName",
                                                    "label": "编号"
                                                },
                                                {
                                                    "name": "name",
                                                    "label": "名称"
                                                }
                                            ],
                                            "messages": {
                                            },
                                            "keepItemSelectionOnPageChange": false,
                                            "syncLocation": true,
                                            "label": "Browser",
                                            "sortable": true,
                                            "searchable": true,
                                            "toggled": true,
                                            "columnsTogglable": false
                                        },
                                        "modalMode": "drawer",
                                        "embed": false,
                                        "inputClassName": "w-xxl",
                                        "multiple": false,
                                        "disabledOn": "",
                                        "requiredOn": "this.tree",
                                        "columnRatio": "auto",
                                        "id": "u:f2f83b86c54d",
                                        "mode": "horizontal",
                                        "inline": true,
                                        "className": "w650"
                                    }
                                ],
                                "label": false,
                                "gap": "md",
                                "id": "u:9900dfe08ba3"
                            },
                            {
                                "type": "group",
                                "body": [
                                    {
                                        "type": "switch",
                                        "label": "抽象类",
                                        "name": "abstractClass",
                                        "option": "",
                                        "mode": "inline",
                                        "optionAtLeft": false,
                                        "trueValue": true,
                                        "falseValue": false,
                                        "value": false,
                                        "id": "u:51d7cb0981ee"
                                    },
                                    {
                                        "type": "switch",
                                        "label": "物理删除",
                                        "name": "physicalDelete",
                                        "option": "",
                                        "mode": "inline",
                                        "optionAtLeft": false,
                                        "trueValue": true,
                                        "falseValue": false,
                                        "value": false,
                                        "id": "u:4c76b9dec6e8"
                                    },
                                    {
                                        "type": "switch",
                                        "label": "开启缓存",
                                        "name": "enableCache",
                                        "mode": "inline",
                                        "option": "",
                                        "optionAtLeft": false,
                                        "trueValue": true,
                                        "falseValue": false,
                                        "value": false,
                                        "id": "u:c51efdd8d687"
                                    },
                                    {
                                        "type": "combo",
                                        "label": "",
                                        "name": "cacheConfig",
                                        "visibleOn": "this.enableCache==true",
                                        "joinValues": true,
                                        "multiple": false,
                                        "multiLine": true,
                                        "className": "fixHeight",
                                        "messages": {
                                        },
                                        "noBorder": true,
                                        "disabledOn": "",
                                        "items": [
                                            {
                                                "type": "switch",
                                                "label": "是否本地缓存",
                                                "name": "cacheType",
                                                "mode": "horizontal",
                                                "option": "",
                                                "description": "是为本地缓存，否为远端缓存（Redis）",
                                                "optionAtLeft": false,
                                                "trueValue": "NATIVE",
                                                "falseValue": "REMOTE",
                                                "value": "NATIVE"
                                            }
                                        ],
                                        "mode": "inline",
                                        "id": "u:4610079d13bc"
                                    }
                                ],
                                "label": false,
                                "id": "u:0df4246ee659",
                                "gap": "md",
                                "subFormMode": ""
                            },
                            {
                                "type": "group",
                                "body": [
                                    {
                                        "type": "select",
                                        "label": "继承策略",
                                        "name": "strategy",
                                        "options": [
                                            {
                                                "label": "共享",
                                                "value": "share"
                                            },
                                            {
                                                "label": "连接",
                                                "value": "joined"
                                            },
                                            {
                                                "label": "复制",
                                                "value": "copy"
                                            }
                                        ],
                                        "mode": "inline",
                                        "checkAll": false,
                                        "size": "sm",
                                        "value": "joined",
                                        "id": "u:60ba43a990c5",
                                        "multiple": false
                                    },
                                    {
                                        "type": "select",
                                        "label": "作用域",
                                        "name": "scope",
                                        "options": [
                                            {
                                                "label": "企业",
                                                "value": "company"
                                            },
                                            {
                                                "label": "应用",
                                                "value": "app"
                                            },
                                            {
                                                "label": "模块",
                                                "value": "moudle"
                                            }
                                        ],
                                        "mode": "horizontal",
                                        "checkAll": false,
                                        "value": "app",
                                        "size": "sm",
                                        "id": "u:ed8952a270de"
                                    }
                                ],
                                "label": false,
                                "id": "u:1c519ad08ab1"
                            }
                        ],
                        "className": "Collapse--sm",
                        "id": "u:ecdd10d91502",
                        "collapsable": false,
                        "subFormMode": "horizontal"
                    },
                    {
                        "type": "fieldset",
                        "title": "关联值对象",
                        "collapsable": false,
                        "body": [
                            {
                                "type": "input-table",
                                "label": "",
                                "name": "voList",
                                "draggable": false,
                                "columns": [
                                    {
                                        "label": "模型",
                                        "name": "modelId",
                                        "placeholder": "-",
                                        "quickEdit": {
                                            "mode": "horizontal",
                                            "type": "picker",
                                            "label": "",
                                            "name": "modelId",
                                            "joinValues": true,
                                            "valueField": "id",
                                            "labelField": "name",
                                            "source": "${platformUrl | url_decode}/api/v1/engine/model/getListByParam?scopeId=${fullroute}&subType=VO&isExtend=FALSE",
                                            "size": "lg",
                                            "pickerSchema": {
                                                "mode": "table",
                                                "name": "",
                                                "draggable": false,
                                                "headerToolbar": [
                                                ],
                                                "columns": [
                                                    {
                                                        "name": "enName",
                                                        "label": "编号"
                                                    },
                                                    {
                                                        "name": "name",
                                                        "label": "名称"
                                                    }
                                                ],
                                                "messages": {
                                                },
                                                "keepItemSelectionOnPageChange": false,
                                                "syncLocation": true,
                                                "label": "Browser",
                                                "sortable": true,
                                                "searchable": true,
                                                "toggled": true,
                                                "source": "",
                                                "perPageField": "rows"
                                            },
                                            "modalMode": "drawer",
                                            "embed": false,
                                            "inputClassName": "",
                                            "multiple": false,
                                            "disabledOn": "",
                                            "id": "u:cef4316f3f3e"
                                        },
                                        "fixed": "",
                                        "toggled": true,
                                        "className": "",
                                        "width": "",
                                        "id": "u:22cbf9b1768c"
                                    },
                                    {
                                        "label": "类型",
                                        "name": "type",
                                        "placeholder": "-",
                                        "quickEdit": {
                                            "type": "select",
                                            "options": [
                                                {
                                                    "label": "嵌入的",
                                                    "value": "embedded"
                                                },
                                                {
                                                    "label": "集合关联",
                                                    "value": "collection"
                                                }
                                            ],
                                            "mode": "popOver",
                                            "checkAll": false,
                                            "name": "type",
                                            "required": true,
                                            "visibleOn": "this.modelId",
                                            "id": "u:ced99abfca9a"
                                        },
                                        "fixed": "",
                                        "toggled": true,
                                        "value": "embedded",
                                        "id": "u:d0f118c908c5"
                                    }
                                ],
                                "addable": true,
                                "removable": true,
                                "mode": "normal",
                                "columnsTogglable": false,
                                "needConfirm": false,
                                "inline": true,
                                "disabledOn": "",
                                "visibleOn": "",
                                "visible": "",
                                "disabled": "",
                                "inputClassName": "m-none m-t-lg",
                                "strictMode": true,
                                "id": "u:e02618c0e076"
                            }
                        ],
                        "subFormMode": "horizontal",
                        "className": "Collapse--sm",
                        "id": "u:c93e8cab1f74"
                    },
                    {
                        "type": "fieldset",
                        "title": "关联关系",
                        "collapsable": false,
                        "body": [
                            {
                                "type": "input-table",
                                "label": "",
                                "name": "relation",
                                "draggable": false,
                                "columns": [
                                    {
                                        "label": "关联模型",
                                        "name": "modelId",
                                        "placeholder": "-",
                                        "quickEdit": {
                                            "mode": "horizontal",
                                            "type": "picker",
                                            "label": "",
                                            "name": "modelId",
                                            "joinValues": true,
                                            "valueField": "id",
                                            "labelField": "enName",
                                            "source": {
                                                "method": "get",
                                                "url": "${platformUrl | url_decode}/api/v1/engine/domainmodel/",
                                                "data": {
                                                    "modelType": "domainmodel",
                                                    "moudleId": "${mid.moudleId}",
                                                    "protocol": "bd",
                                                    "filterKey": "id",
                                                    "&": "$$"
                                                }
                                            },
                                            "size": "lg",
                                            "pickerSchema": {
                                                "mode": "table",
                                                "name": "",
                                                "columns": [
                                                    {
                                                        "name": "enName",
                                                        "label": "编号"
                                                    },
                                                    {
                                                        "name": "name",
                                                        "label": "名称"
                                                    }
                                                ],
                                                "messages": {
                                                },
                                                "keepItemSelectionOnPageChange": false,
                                                "syncLocation": true,
                                                "headerToolbar":[
                                                ],
                                                "filter":{
                                                    "body":[
                                                        {
                                                            "type": "input-text",
                                                            "name": "keyword",
                                                            "addOn": {
                                                                "type": "submit",
                                                                "label": "搜索",
                                                                "level": "primary",
                                                                "icon": "fa fa-search pull-left",
                                                                "id": "u:efc6d0be93b1"
                                                            },
                                                            "id": "u:2e566d5622bb",
                                                            "mode": "inline"
                                                        }
                                                    ],
                                                    "wrapWithPanel": false
                                                },
                                                "draggable": false,
                                                "label": "Browser",
                                                "sortable": false,
                                                "searchable": true,
                                                "toggled": false,
                                                "source": "",
                                                "perPageField": "rows",
                                                "pageField": "page",
                                            },
                                            "modalMode": "drawer",
                                            "embed": false,
                                            "inputClassName": "",
                                            "multiple": false,
                                            "disabledOn": "",
                                            "id": "u:cddf0f3186dd"
                                        },
                                        "fixed": "",
                                        "toggled": true,
                                        "className": "",
                                        "width": "",
                                        "id": "u:3ed6e386e46c"
                                    },
                                    {
                                        "label": "类型",
                                        "name": "type",
                                        "placeholder": "-",
                                        "quickEdit": {
                                            "type": "select",
                                            "options": [
                                                {
                                                    "label": "一对一",
                                                    "value": "oneToOne"
                                                },
                                                {
                                                    "label": "一对多",
                                                    "value": "oneToMany"
                                                },
                                                {
                                                    "label": "多对一",
                                                    "value": "manyToOne"
                                                },
                                                {
                                                    "label": "多对多",
                                                    "value": "manyToMany"
                                                }
                                            ],
                                            "mode": "popOver",
                                            "checkAll": false,
                                            "name": "type",
                                            "id": "u:16c1f24fb1ee"
                                        },
                                        "fixed": "",
                                        "id": "u:44d4bb4e0990"
                                    },
                                    {
                                        "label": "关联主键",
                                        "name": "primaryKey",
                                        "placeholder": "-",
                                        "id": "u:0158b2fde295"
                                    }
                                ],
                                "addable": true,
                                "removable": true,
                                "mode": "normal",
                                "columnsTogglable": false,
                                "needConfirm": false,
                                "inline": true,
                                "disabledOn": "",
                                "visibleOn": "",
                                "visible": "",
                                "disabled": "",
                                "inputClassName": "m-none m-t-lg",
                                "id": "u:8e084d711c9a"
                            }
                        ],
                        "className": "Collapse--sm",
                        "id": "u:3c7bd7ebd026"
                    }
                ],
                "title": "",
                "mode": "horizontal",
                "api": "/saveForm",
                "actions": [
                ],
                "id": getAmisId(option)
            },
            props:{
                // data:option.data
                data:{...utils.getGlobalEnv(option.data.data),...modelJson}
            },
        })

        option.grid_domain_design_index = domain_design_index.render({
            elem: '#' + getDmainDesignIndex(option),
            initData: initDomainIndex
        })

        $('#' + getGridDomainDesignDefault(option)).parents('.layui-tab-item').eq(0).removeClass('layui-show');

        $('#' + getDmainDesignIndex(option)).parents('.layui-tab-item').eq(0).removeClass('layui-show');
    }

    // configur();
    exports(MOD_NAME, new domain_design());

});
